﻿using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonHelper
{
    public static class ConsulHelper
    {
        public static void ConsulRegistry(this IConfiguration configuration, IApplicationBuilder app)
        {
            try
            {
                // 获取主机生命周期管理接口
                var lifetime = app.ApplicationServices.GetRequiredService<IHostApplicationLifetime>();
                
                string envType = configuration.GetSection("AgileConfig")["env"];         
                string agileKey = string.Empty;
                if (envType == "DEV")
                {
                    //Dev
                     agileKey = configuration["OrderServiceDev:OrderServiceAppsettings.json"];
                }
                else
                {
                    //Pro
                     agileKey = configuration["OrderServicePro:OrderServiceProAppsettings"];
                }
                JObject config = JObject.Parse(agileKey);
                string ip = configuration["ip"].ToString();
                string port = configuration["port"].ToString();
                string weight = configuration["weight"].ToString();
                string consulAddress = config["ConsulAddress"].ToString();
                string consulCenter = config["ConsulCenter"].ToString();

                string connectionString = config["ConnectionStrings"]["dbConnections"].ToString();
                
                //测试内存使用率

                //测试获取配置文件节点值
                string nicai = configuration.GetSection("AgileConfig")["tag"]; 

                ConsulClient client = new ConsulClient(c =>
                {
                    c.Address = new Uri(consulAddress);
                    c.Datacenter = consulCenter;
                });


                var serviceId = "OrderService " + Guid.NewGuid();
                client.Agent.ServiceRegister(new AgentServiceRegistration()
                {
                    ID = serviceId,  //唯一的
                    Name = "OrderService", //分组---根据Service名字
                    Address = ip,
                    Port = int.Parse(port),
                    Tags = new string[] { weight.ToString() },//额外标签信息
                    //添加心跳检测
                    Check = new AgentServiceCheck()
                    {
                        Interval = TimeSpan.FromSeconds(12),        //心跳时间间隔
                        HTTP = $"http://{ip}:{port}/api/Health/Index",  //心跳的http地址
                        Timeout = TimeSpan.FromSeconds(5),          //超时参数
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(15)//超时后consul取消异常服务注册；
                    }
                });
                Console.WriteLine($"{ip}:{port}---weight:{weight}"); // 命令行参数获取

                // 应用程序终止时，服务取消注册
                lifetime.ApplicationStopping.Register(() =>
                {
                    client.Agent.ServiceDeregister(serviceId).Wait();
                });
            }
            catch(Exception ex)
            {
                Console.WriteLine($"Consul注册:{ex.Message}");
            }
        }
    }
}
